package com.da.lon.wang.xlg.adapter;

import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.CheckInfoResultBean.CheckValue;
import com.da.lon.wang.xlg.bean.CheckInfoResultBean.OrderAddress;
import com.da.lon.wang.xlg.bean.CheckInfoResultBean.cart_result;
import com.da.lon.wang.xlg.util.LogUtils;

import java.util.ArrayList;

public class OrderAdapter extends BaseAdapter implements OnClickListener {

    private LayoutInflater inflater;
    private Context context = null;
    CallBack1 myCallBack;

    private ArrayList<cart_result> datas;
    private ArrayList<CheckValue> value;
    private OrderAddress orderAddress;
    private String couponcount = null;
    private String couponId = null;
    private String isinvoice = null;
    private String invoiceString = null;
    private String dqmoney = null;
    private String totalAmount = null;
    private String totalCount = null;
    private StringBuffer qcontent;
    Holder1 holder;
    protected int touchedPosition =-1;
    public boolean focuse_ok;
    private int screenHeight;
    private int keyHeight;
    protected boolean fa= false;
    public boolean tiok;
    protected String ouka_order_message_before;

    public OrderAdapter(Context context, ArrayList<cart_result> datas, OrderAddress orderAddress, String couponcount,
                        String couponId, String isinvoice, String invoiceString, String dqmoney, String totalAmount,
                        String totalCount, CallBack1 myCallBack) {
        this.context = context;
        this.datas = datas;
        this.orderAddress = orderAddress;
        this.myCallBack = myCallBack;
        this.couponcount = couponcount;
        this.couponId = couponId;
        this.isinvoice = isinvoice;
        this.invoiceString = invoiceString;
        this.dqmoney = dqmoney;
        this.totalAmount = totalAmount;
        this.totalCount = totalCount;
        value = new ArrayList<CheckValue>();
        inflater = LayoutInflater.from(context);
        qcontent = new StringBuffer();
        qcontent.append("{");
        holder = new Holder1();
        init();
    }

    // 初始化 留言信息
    private void init() {
        try {
            ArrayList<cart_result> data_cart_result_list = MyApplication.getInstance().getDatas();
            if(data_cart_result_list!=null && data_cart_result_list.size()>0){
                int le = data_cart_result_list.size() >= datas.size()?datas.size():data_cart_result_list.size();
                for (int i=0 ;i<le;i++) {
                    if(data_cart_result_list.get(i).getValue().get(0).getId().equals(datas.get(i).getValue().get(0).getId())){
                        datas.get(i).setLeave_message(data_cart_result_list.get(i).getLeave_message());
                    }
                }
            }
            MyApplication.getInstance().setDatas(datas);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getCount() {
        return datas!=null?datas.size() + 2:2;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        try {
            if (position == 0) {
                // 列表头部
                convertView = inflater.inflate(R.layout.ouka_order_listview_header, null);

                // 收货地址
                holder.addressLayout = (LinearLayout) convertView.findViewById(R.id.order_address);
                holder.addressnullLayout = (LinearLayout) convertView.findViewById(R.id.address_null);
                holder.nameView = (TextView) convertView.findViewById(R.id.order_address_name);
                holder.phoneView = (TextView) convertView.findViewById(R.id.order_address_phone);
                holder.addressView = (TextView) convertView.findViewById(R.id.order_address_location);

                if (orderAddress != null) {
                    holder.addressLayout.setVisibility(View.VISIBLE);
                    holder.addressnullLayout.setVisibility(View.GONE);
                    holder.addressLayout.setOnClickListener(this);
                    holder.nameView.setText(orderAddress.getReal_name());
                    holder.phoneView.setText(orderAddress.getTelphone());
                    if(orderAddress.getCounty_name()==null){
                        holder.addressView.setText("收货地址: " + orderAddress.getProvinceid_name() + orderAddress.getCity_name()
                                + orderAddress.getAddress());

                    }else{
                        holder.addressView.setText("收货地址: " + orderAddress.getProvinceid_name() + orderAddress.getCity_name()
                                + orderAddress.getCounty_name() + orderAddress.getAddress());

                    }
                } else {
                    holder.addressLayout.setVisibility(View.GONE);
                    holder.addressnullLayout.setVisibility(View.VISIBLE);
                    holder.addressnullLayout.setOnClickListener(this);
                }

                // 优惠券
                holder.couponLayout = (LinearLayout) convertView.findViewById(R.id.order_coupon_check);
                holder.couponLayout.setOnClickListener(this);
                holder.couponView = (TextView) convertView.findViewById(R.id.order_coupon_tv);
                if (couponId == null) {
                    if (couponcount != null && Integer.parseInt(couponcount) != 0) {
                        holder.couponView.setText("您有可用优惠券");
                    } else {
                        holder.couponView.setText(R.string.no_coupons);
                    }
                } else {
                    holder.couponView.setText("已使用优惠券");
                }

            } else if (position == datas.size() + 1) {
                // 列表尾部
                convertView = inflater.inflate(R.layout.ouka_order_listview_footer, null);

                // 发票信息
                holder.billLayout = (LinearLayout) convertView.findViewById(R.id.order_bill_check);
                holder.billTextView = (TextView) convertView.findViewById(R.id.order_bill_tv);

                if (isinvoice != null) {
                    if (Integer.parseInt(isinvoice) == 1) {
                        holder.billLayout.setVisibility(View.GONE);
                    } else if (Integer.parseInt(isinvoice) == 0) {
                        holder.billLayout.setVisibility(View.VISIBLE);
                        holder.billLayout.setOnClickListener(this);
                        if (invoiceString != null) {
                            holder.billTextView.setText(invoiceString + "\n" +
                                    convertView.getContext().getString(R.string.individual));
                        }
                    }
                }

                // 商品合计
                holder.countTextView = (TextView) convertView.findViewById(R.id.order_count_all);
                holder.priceTextView = (TextView) convertView.findViewById(R.id.order_price_all);
                holder.dqmoneyTextView = (TextView) convertView.findViewById(R.id.order_dqmoney);
                holder.countTextView.setText(convertView.getContext().getString(R.string.piece_goods, totalCount));
                holder.priceTextView.setText(totalAmount);
                if (dqmoney == null || "".equals(dqmoney)) {
                    holder.dqmoneyTextView.setVisibility(View.GONE);
                } else {
                    holder.dqmoneyTextView.setVisibility(View.VISIBLE);
                    holder.dqmoneyTextView.setText("(已优惠" + dqmoney + ")");
                }

            } else {
                // 商品列表
                convertView = inflater.inflate(R.layout.ocoffee_order_list_item, null);

                holder.listView = (ListView) convertView.findViewById(R.id.order_list_item_lv);
                holder.activityRootView = (LinearLayout) convertView.findViewById(R.id.root_layout);
                //获取屏幕高度
                screenHeight = ((Activity) context).getWindowManager().getDefaultDisplay().getHeight();
                //阀值设置为屏幕高度的1/3
                keyHeight = screenHeight/3;
                holder.areaTextView = (TextView) convertView.findViewById(R.id.ouka_order_area);
                holder.fareTextView = (TextView) convertView.findViewById(R.id.ouka_order_fare);
                holder.taxTextView = (TextView) convertView.findViewById(R.id.ouka_order_tax);
                holder.itemtotalTextView = (TextView) convertView.findViewById(R.id.ouka_order_itemtotal);
                holder.itemtotal1TextView = (TextView) convertView.findViewById(R.id.ouka_order_itemtotal1);
                holder.ouka_order_message = (EditText) convertView.findViewById(R.id.ouka_order_message);

                cart_result cartResult = datas.get(position - 1);
                holder.ouka_order_message.setTag(position);
                holder.ouka_order_message.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
                holder.ouka_order_message.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            touchedPosition = position;
                            fa = true;
                        }
                        return false;
                    }
                });

                class MyTextWatcher implements TextWatcher {
                    public MyTextWatcher(Holder1 holder) {
                        mHolder = holder;
                    }

                    private Holder1 mHolder;

                    @Override
                    public void onTextChanged(CharSequence s, int start,
                                              int before, int count) {

                        LogUtils.v("onTextChanged*******************"+s);
                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start,
                                                  int count, int after) {
                        LogUtils.v("beforeTextChanged*******************" +s);
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (s != null && !"".equals(s.toString())) {
                            int position = (Integer) mHolder.ouka_order_message.getTag();
                            // 当EditText数据发生改变的时候存到data变量中
                            datas.get(position - 1).setLeave_message(s.toString());
                            MyApplication.getInstance().setDatas(datas);
                        }
                        fa = false;
                        LogUtils.v("afterTextChanged*******************"+s);
                    }
                }


                holder.ouka_order_message.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId,
                                                  KeyEvent event) {
                        // TODO Auto-generated method stub
                        /*判断是否是“GO”键*/
                        LogUtils.v("setOnEditorActionListener*******************");
                        if(actionId == EditorInfo.IME_ACTION_NONE){
                            /*隐藏软键盘*/
                            LogUtils.v("没有动作*******************");
                            InputMethodManager imm = (InputMethodManager) v
                                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                            if (imm.isActive()) {
                                imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                                return true;
                            }
                            /*判断是否是“DONE”键*/
                        }else if(actionId == EditorInfo.IME_ACTION_DONE){
                            InputMethodManager imm = (InputMethodManager) v
                                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                            if (imm.isActive()) {
                                imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                                touchedPosition=-1;
                                return true;
                            }
                        }
                        return false;
                    }
                });

                if(datas.size()==1){
                    holder.areaTextView.setText(context.getString(R.string.delivery_address_colon, cartResult.getAr_name()));
                }else{
                    holder.areaTextView.setText("包裹" + position +": " + cartResult.getAr_name());
                }
                holder.fareTextView.setText("￥" + cartResult.getShippingmoney());
                holder.taxTextView.setText(cartResult.getTaxrate());
                holder.itemtotalTextView.setText("共" + cartResult.getNum_count() + "件    合计:  ￥");
                holder.itemtotal1TextView.setText(cartResult.getTotal());
                holder.ouka_order_message.setText(cartResult.getLeave_message());
                LogUtils.v("执行adapter***************************");
                if (touchedPosition == position && fa ) {
                    // 如果当前的行下标和点击事件中保存的index一致，手动为EditText设置焦点。
                    holder.ouka_order_message.requestFocus();
                }else {
                    holder.ouka_order_message.clearFocus();
                }
                holder.ouka_order_message.addTextChangedListener(new MyTextWatcher(holder));
                value = cartResult.getValue();
                holder.adapter = new OrderItemAdapter(context, value);
                holder.listView.setAdapter(holder.adapter);
            }

            if (convertView.getTag() == null) {
                convertView.setTag(holder);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        return convertView;
    }

    /*
     * 回调按钮点击事件到Activity
     */
    public interface CallBack1 {
        public void click(View v);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.order_address:
                // 有收货地址的时候
                myCallBack.click(v);
                break;
            case R.id.address_null:
                // 没有收货地址的时候
                myCallBack.click(v);
                break;
            case R.id.order_coupon_check:
                // 优惠券
                myCallBack.click(v);
                break;
            case R.id.order_bill_check:
                // 发票信息
                myCallBack.click(v);
                break;
            default:
                break;
        }
    }
}

class Holder1 {
    public LinearLayout activityRootView;
    ListView listView;
    OrderItemAdapter adapter;
    TextView areaTextView, fareTextView, taxTextView, itemtotalTextView, itemtotal1TextView;
    EditText ouka_order_message;
    // 列表头部
    LinearLayout addressLayout, addressnullLayout;
    TextView nameView, phoneView, addressView;
    LinearLayout couponLayout;
    TextView couponView;

    // 列表尾部
    LinearLayout billLayout;
    TextView billTextView, countTextView, priceTextView, dqmoneyTextView;
}
